/**
 * 
 */
package org.jugjobs.botrepellent;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author lhaslup
 *
 */
public class BotRepellentServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public final static String DIGIT_IMAGE = "digitImage";
	public final static String CHALLENGE_IMAGE = "challengeImage";
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		HttpSession session = req.getSession();
        ServletContext sc = getServletContext();
		BotRepellent br = new BotRepellent();
		
		String digitImageValue = req.getParameter(DIGIT_IMAGE);
		if(digitImageValue!=null) {
			// decide which digit of the challenger is desired.
			int desiredImage = Integer.parseInt(digitImageValue);
	        // Get the absolute path of the image
	        String filename = sc.getRealPath("WEB-INF/"+br.getDigitImage(session, desiredImage));
	        
	        returnNamedImage(resp, sc, filename);
		} 
		else if(req.getParameter(CHALLENGE_IMAGE)!=null) {
			String filename = sc.getRealPath("WEB-INF/"+br.getImageChallengeImage(session));
			returnNamedImage(resp, sc, filename);
		}
     }
	
	private void returnNamedImage(HttpServletResponse resp, ServletContext sc, String filename) throws IOException {
        // Get the MIME type of the image
        String mimeType = sc.getMimeType(filename);
        if (mimeType == null) {
            sc.log("Could not get MIME type of "+filename);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    
        // Set content type
        resp.setContentType(mimeType);
    
        // Set content size
        File file = new File(filename);
        resp.setContentLength((int)file.length());
    
        // Open the file and output streams
        FileInputStream in = new FileInputStream(file);
        OutputStream out = resp.getOutputStream();
    
        // Copy the contents of the file to the output stream
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        out.close();
		
	}
}
